import { useReady } from '@tarojs/taro'
import { forwardRef, useImperativeHandle, useState } from 'react'
import { AtLoadMore } from 'taro-ui'

import './index.scss'

interface QueryParams {
    [key:string] : any
}

interface Props {
    onClick : {
        (queryParams : QueryParams) : Promise<any[]>
    };

    keyName? : string;

    queryParams? : QueryParams;

    onFinish? : {
        (rows : any[]) : void
    };

    [key : string] : any;
}


export default forwardRef((props:Props, ref) => {
    let keyName = props.keyName || 'id'
    let [pageNo, setpageNo] = useState(0)
    let [status, setStatus] = useState<	'more' | 'loading' | 'noMore'>('more')
    useImperativeHandle(ref, () => {
        return {
            reLoad : () => {
                pageNo = 0
                setStatus('more')
                load()
            }
        }
    })
    async function load() {
        if(status != 'more') return
        let query:QueryParams = {...(props.queryParams || {})}
        query.lastKey = pageNo
        query.pageSize = 20

        setStatus('loading')
        let rows = await props.onClick(query)
        if(rows.length > 0) {
            setpageNo(rows[rows.length][keyName])
        }
        if(rows.length < query.pageSize) {
            setStatus('noMore')
        }else {
            setStatus('more')
        }

        if(props.onFinish) {
            props.onFinish(rows)
        }
    }

    useReady(() => {
        load()
    })

    // useEffect(() => {
    //     load()
    // }, [])


    return (
        <AtLoadMore status={status} moreBtnStyle='border:none;' onClick={() => load()}></AtLoadMore>
    )
})